package com.jlg.util;

import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.lobobrowser.html.AbstractHtmlRendererContext;
import org.lobobrowser.html.FormInput;
import org.lobobrowser.html.HttpRequest;
import org.lobobrowser.html.UserAgentContext;
import org.lobobrowser.html.test.SimpleHttpRequest;
import org.lobobrowser.html.test.SimpleUserAgentContext;

import com.jlg.beans.page.Content;

/*
 * crawl ajax page
 * author: huazhang 
 * since : 2011-3-26
 */
public class CorbaUtil
{
    private static final Logger logger = Logger.getLogger(CorbaUtil.class.getName());
    
    public static Content GetContentWithAjax(String sUrl, String pageEncoding) throws Exception
    {
        UserAgentContext uacontext = new LocalUserAgentContext();
        LocalHtmlRendererContext rcontext = new LocalHtmlRendererContext(uacontext);
        // First, we navigate to the starting location.
        rcontext.navigate(sUrl);
        // Next, we search for a form in the resulting
        // document.
        return rcontext.getContent();
    }
  
    private static class LocalUserAgentContext extends SimpleUserAgentContext
    {
        int timeout;
        boolean persistent;

        public LocalUserAgentContext()
        {
            super();
        }

        public LocalUserAgentContext(int timeout, boolean persistent)
        {
            super();
            this.timeout = timeout;
            this.persistent = persistent;
        }

        public HttpRequest createHttpRequest()
        {
            return new CobraHttpRequest(this, this.getProxy(), timeout, persistent);
        }

        @Override
        public boolean isScriptingEnabled()
        {
            return true;
        }

        @Override
        public boolean isExternalCSSEnabled()
        {
            return true;
        }

        @Override
        public String getUserAgent()
        {
            return "Mozilla/4.0 (compatible; MSIE 6.0;) Cobra/ScrapingTest Parser Demo";
        }
    }

    private static class LocalHtmlRendererContext extends
            AbstractHtmlRendererContext
    {
        // We need a renderer context to do form submission,
        // but we don't need to extend SimpleHtmlRendererContext
        // which is a GUI-based context. This simple
        // implementation should be enough.
        private final UserAgentContext uacontext;
        private Content content;

        public LocalHtmlRendererContext(final UserAgentContext uacontext)
        {
            this.uacontext = uacontext;
        }

        public Content getContent()
        {
            // This field is set by the local submitForm()
            // implementation.
            return this.content;
        }

        @Override
        public boolean isImageLoadingEnabled()
        {
            // We don't need to load images.
            return false;
        }

        @Override
        public UserAgentContext getUserAgentContext()
        {
            // For consistency, this should return the
            // same UserAgentContext that was used to
            // parse the document.
            return this.uacontext;
        }

        public void navigate(String urlOrPath)
        {
            try
            {
                // We implement a convenience navigate() method
                // that is based on submitForm().
                URL url = org.lobobrowser.util.Urls.guessURL(urlOrPath);
                this.submitForm("GET", url, "_this", null, null);
            } catch (java.net.MalformedURLException mfu)
            {
                logger.log(Level.WARNING, "navigate()", mfu);
            }
        }

        @Override
        public void submitForm(String method, URL action, String target,
                String enctype, FormInput[] formInputs)
        {
            String url = HttpUtil.getUrl(action);
            try
            {
                this.content = HttpUtil.GetContent(url, null, false);
            } catch (Exception e)
            {
                this.content = null;
                e.printStackTrace();
            }
        }
    }
}

class CobraHttpRequest extends SimpleHttpRequest
{
    /** The read timeout and connection timeout in milliseconds. */
    int timeout = 1000 * 60 * 30;
    /**
     * If false, HttpRequest objects have the "Connection : close" property set
     * to discourage persistent connections.
     */
    boolean persistent = false;

    /**
     * Create an HttpRequest object whose open() methods create URLConnection
     * objects with timeout and persistence values.
     */
    public CobraHttpRequest(UserAgentContext context, java.net.Proxy proxy,
            int timeout, boolean persistence)
    {
        super(context, proxy);
        this.timeout = timeout;
        this.persistent = persistent;
    }

    /**
     * Override the primary open() method so that the URLConnection object can
     * be configured.
     */
    public void open(final String method, final java.net.URL url,
            boolean asyncFlag, final String userName, final String password)
            throws java.io.IOException
    {
        super.open(method, url, asyncFlag, userName, password);
        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(timeout);
        if (!persistent)
        {
            connection.setRequestProperty("Connection", "close");
        }
    }

}
